
from fastapi import FastAPI, Request
from pydantic import BaseModel
import uvicorn
from loguru import logger
import time
import requests  # 用HTTP API替代Nacos SDK，稳定无兼容问题
from typing import Optional
# 原错误导入
# from distributed_agent.agent_service import AgentRequest, AgentResponse

# 修正后的导入
from agent_service import AgentRequest, AgentResponse
# from distributed_agent.agent_service import AgentRequest, AgentResponse

# -------------------------- 服务初始化 --------------------------
app = FastAPI(title="Multi Mode Agent Service")
# multimodal_agent_service.py
SERVICE_NAME = "multimodal_agent_service"
AGENT_PORT = 8002

# 在multimodal_agent_service.py中添加Nacos注册（参考agent_service.py）
NACOS_SERVER = "http://192.168.150.101:8848"
# 1. 自动获取本机 IP（别写死！）
import socket
def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 1))
    ip = s.getsockname()[0]
    s.close()
    return ip
print("🔥 正在运行 multimodal_agent_service.py（端口 8002）")
AGENT_IP = get_local_ip()  # 替换原来的 "192.168.52.1"
AGENT_PORT = 8002
SERVICE_NAME = "multimodal_agent_service"
NACOS_NAMESPACE = ""

def register_to_nacos():
    url = f"{NACOS_SERVER}/nacos/v1/ns/instance"
    params = {
        "serviceName": SERVICE_NAME,
        "ip": AGENT_IP,
        "port": AGENT_PORT,
        "weight": 10.0,
        "metadata": '{"version":"v1.0","type":"multimodal"}',
        "ephemeral": "true",
        "clusterName": "DEFAULT",
        "namespaceId": NACOS_NAMESPACE
    }
    try:
        response = requests.post(url, params=params, timeout=5)
        # 只要状态码是 200 或 201 就算成功（Nacos 成功时通常返回 200 + 空 body）
        return response.status_code in (200, 201)
    except Exception as e:
        print(f"注册异常: {e}")
        return False

 # if not register_to_nacos():
#     exit(1)



# 核心接口：生成图像
@app.post("/agent/multimodal/invoke", response_model=AgentResponse)
async def invoke_multimodal_agent(req: AgentRequest):
    try:
        # 调用Stable Diffusion（简化示例）
        from diffusers import StableDiffusionPipeline
        pipeline = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
        image = pipeline(req.query).images[0]
        image_url = upload_to_storage(image)  # 上传至对象存储
        return AgentResponse(
            code=200,
            data=image_url,
            message="success",
            trace_id=req.trace_id
        )
    except Exception as e:
        return AgentResponse(code=500, data="", message=str(e), trace_id=req.trace_id)


def upload_to_storage(image):
    import io
    import requests
    from datetime import datetime

    # 将 PIL Image 转为字节流
    img_byte_arr = io.BytesIO()
    image.save(img_byte_arr, format='PNG')
    img_byte_arr.seek(0)

    files = {'file': (f"img_{datetime.now().strftime('%Y%m%d%H%M%S')}.png", img_byte_arr, 'image/png')}
    response = requests.post("http://your-file-server/upload", files=files)

    if response.status_code == 200:
        return response.json().get("url")  # 假设返回 {"url": "..."}
    else:
        raise Exception("文件上传失败")



# 2. 把注册逻辑移到 main 里（防止导入就注册）
if __name__ == "__main__":
    if not register_to_nacos():
        print("❌ 注册失败，退出")
        exit(1)
    uvicorn.run(app, host="0.0.0.0", port=AGENT_PORT, log_config=None)
    # invoke_multimodal_agent()